package com.xiaocq.wordskiller;

import java.util.ArrayList;
import java.util.List;

import com.xiaocq.wordskiller.db.DatabaseHelper;
import com.xiaocq.wordskiller.db.VocabularyDatabase.VocabularyMeta;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class CostumTest extends Activity {
	private static final String TAG = "CostumTest";

	private static final int SHOW_CONFIRM_DIALOG = 1;
	private static final int SHOW_COUNTS_SELECT_DIALOG = 2;
	private static final int SHOW_INPUT_DIALOG = 3;
	private static final int SHOW_NEW_TEST_CONFIRM_DIALOG = 4;

	private Spinner testTypeSelect;
	private TextView testProgressShow;
	private Button testCountSelect, startTest,resetTest,backToMenu,testModelSelect;
	
	private boolean testModel;
	private int mTestType;
	private int mFinishedTest;
	private int mTestCounts = 30;
	private boolean isNewTest;
	private long allTimeInMillis;
	private int allCounts,undoCounts,doCounts,correctCounts,wrongCounts;
	
	private SharedPreferences pref;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.costumtest);

		initComponents();

		loadOrInit();
	}

	private void initComponents() {
		testTypeSelect = (Spinner) findViewById(R.id.costumtest_testTypeSelect);
		testCountSelect = (Button) findViewById(R.id.costumtest_testCountsSelect);
		startTest = (Button) findViewById(R.id.costumtest_startTest);
		resetTest = (Button) findViewById(R.id.costumtest_resetTest);
		backToMenu = (Button) findViewById(R.id.costumtest_backToMenu);
		testProgressShow = (TextView) findViewById(R.id.costumtest_testProgressShow);
		testModelSelect = (Button) findViewById(R.id.costumtest_testModelSelect);

		ArrayAdapter<String> adapter = getData();
		testTypeSelect.setAdapter(adapter);
		testTypeSelect.setOnItemSelectedListener(new OnItemSelectedListener() {
			
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				mTestType = position;
				setComponents();
			}
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
		
		testModelSelect.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				testModel = !testModel;
				testModelSelect.setText(testModel ? R.string.tip_completion : R.string.tip_multipleChoice);
			}
		});
		
		testCountSelect.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(SHOW_COUNTS_SELECT_DIALOG);
			}
		});
		
		resetTest.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(SHOW_NEW_TEST_CONFIRM_DIALOG);
			}
		});
		
		startTest.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if(mTestCounts == 0){
					Toast.makeText(CostumTest.this, R.string.tip_error, Toast.LENGTH_SHORT).show();
					return;
				}
				Intent intent = new Intent(testModel ? CommandList.COSTUM_COMPLETION_TEST : CommandList.COSTUM_CHOICE_TEST);
				intent.putExtra(CommandList.IS_THE_NEW_TEST, isNewTest);
				intent.putExtra(CommandList.COSTUM_TEST_TYPE, mTestType);
				intent.putExtra(CommandList.COSTUM_TEST_COUNTS, mTestCounts);
				intent.putExtra(CommandList.COSTUM_FINISHED_COUNTS, mFinishedTest);
				intent.putExtra(CommandList.COSTUM_TIME_COST, allTimeInMillis);
				startActivity(intent);
				finish();
			}
		});
		
		backToMenu.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		
		setComponents();
	}
	
	private void loadOrInit(){
		pref = getSharedPreferences(CommandList.PREF_NAME, MODE_PRIVATE);
		isNewTest = pref.getBoolean(CommandList.IS_THE_NEW_TEST, true);
		mTestType = pref.getInt(CommandList.COSTUM_TEST_TYPE, -1);
		Log.d(TAG, "isNewTest " + isNewTest + " mTestType " + mTestType);
		if (!isNewTest && (mTestType != -1)) {
			showDialog(SHOW_CONFIRM_DIALOG);
		}else{
			initNewTest();
		}
	}
	
	private ArrayAdapter<String> getData(){
		List<String> data = getCurrentCounts();
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		return adapter;
	}
	

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case SHOW_CONFIRM_DIALOG:
			return new AlertDialog.Builder(this)
					.setMessage(R.string.tip_loadOrNot)
					.setPositiveButton(android.R.string.ok,
							new OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									loadLastTest();
								}
							})
					.setNegativeButton(android.R.string.cancel,
							new OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									initNewTest();
								};
							}).create();
		case SHOW_COUNTS_SELECT_DIALOG:
			return new AlertDialog.Builder(this)
				.setItems(R.array.test_counts_values, new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						switch(which){
						case 0:
							mTestCounts = 30;
							break;
						case 1:
							mTestCounts = 50;
							break;
						case 2:
							mTestCounts = 70;
							break;
						case 3:
							showDialog(SHOW_INPUT_DIALOG);
							break;
						default:
							throw new IllegalArgumentException("错误的选项被选中" + which);
						}
						setComponents();
					}
				}).create();
		case SHOW_INPUT_DIALOG:
			LayoutInflater inflater = LayoutInflater.from(CostumTest.this);
			final View view = inflater.inflate(R.layout.input_dialog, null);
			final EditText countsInput = (EditText) view.findViewById(R.id.dialog_et_input);
			
			return new AlertDialog.Builder(this)
				.setView(view)
				.setPositiveButton(android.R.string.ok, new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						CharSequence info = countsInput.getText();
						countsInput.setText("");
						if(info.length() != 0){
							mTestCounts = Integer.valueOf(info.toString());
						}else{
							mTestCounts = 0;
						}
						setComponents();
					}
				})
				.setNegativeButton(android.R.string.cancel, new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					}
				}).create();
		case SHOW_NEW_TEST_CONFIRM_DIALOG:
			return new AlertDialog.Builder(this)
				.setMessage(R.string.tip_resetOrNot)
				.setPositiveButton(android.R.string.ok, new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						initNewTest();
					}
				})
				.setNegativeButton(android.R.string.cancel, new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					}
				}).create();
		default:
			return super.onCreateDialog(id);
		}
	}
	
	private void loadLastTest(){
		testModel = pref.getBoolean(CommandList.COSTUM_TEST_MODEL, false);
		mTestCounts = pref.getInt(CommandList.COSTUM_TEST_COUNTS, 30);
		mFinishedTest = pref.getInt(CommandList.COSTUM_FINISHED_COUNTS, 0);
		allTimeInMillis = pref.getLong(CommandList.COSTUM_TIME_COST, 0L);
		
		testModelSelect.setText(testModel ? R.string.tip_completion : R.string.tip_multipleChoice);
		testTypeSelect.setSelection(mTestType);
		
		testTypeSelect.setEnabled(false);
		testCountSelect.setEnabled(false);
		testModelSelect.setEnabled(false);
		
		setComponents();
	}
	
	private void initNewTest(){
		mTestCounts = 30;
		mTestType = 0;
		mFinishedTest = 0;
		allTimeInMillis = 0L;
		isNewTest = true;
		testModel = false;
		
		if(!testTypeSelect.isEnabled()) testTypeSelect.setEnabled(true);
		if(!testCountSelect.isEnabled()) testCountSelect.setEnabled(true);
		if(!testModelSelect.isEnabled()) testModelSelect.setEnabled(true);
		
		testModelSelect.setText(testModel ? R.string.tip_completion : R.string.tip_multipleChoice);
		testTypeSelect.setSelection(mTestType);
		
		setComponents();
	}
	
	private void setComponents(){
		checkAndChangeTestCount();
		
		testCountSelect.setText(mTestCounts + "个");

		String indicate = mFinishedTest + " / " + mTestCounts;
		testProgressShow.setText(indicate);
	}
	
	private void checkAndChangeTestCount(){
		int upLimit = getUpLimit();
		if(mTestCounts == 0) {
			mTestCounts = upLimit > 30 ? 30 : upLimit;
		}else{
			mTestCounts = mTestCounts > upLimit ? upLimit : mTestCounts;
		}
	}
	
	private int getUpLimit(){
		int upLimit = 0;
		switch(mTestType){
		case 0:
			upLimit = allCounts;
			break;
		case 1:
			upLimit = undoCounts;
			break;
		case 2:
			upLimit = doCounts;
			break;
		case 3:
			upLimit = correctCounts;
			break;
		case 4:
			upLimit = wrongCounts;
			break;
		}
		if(upLimit > 250) upLimit = 250;
		return upLimit;
	}
	
	private List<String> getCurrentCounts(){
		List<String> list = new ArrayList<String>();
		String[] items = new String[5];
		DatabaseHelper mOpenHelper = new DatabaseHelper(this);
		SQLiteDatabase db = mOpenHelper.getReadableDatabase();

		Cursor cursor = db.rawQuery("select count(*) from " + VocabularyMeta.TABLE_NAME, null);
		cursor.moveToFirst();
		allCounts = cursor.getInt(0);
		
		cursor = db.rawQuery("select count(*) from " + VocabularyMeta.TABLE_NAME + " where " + VocabularyMeta.ANSWER_STATE + " = ?", new String[]{"0"});
		cursor.moveToFirst();
		undoCounts = cursor.getInt(0);
		
		cursor = db.rawQuery("select count(*) from " + VocabularyMeta.TABLE_NAME + " where " + VocabularyMeta.ANSWER_STATE + " != ?", new String[]{"0"});
		cursor.moveToFirst();
		doCounts = cursor.getInt(0);
		
		cursor = db.rawQuery("select count(*) from " + VocabularyMeta.TABLE_NAME + " where " + VocabularyMeta.ANSWER_STATE + " = ?", new String[]{"1"});
		cursor.moveToFirst();
		correctCounts = cursor.getInt(0);
		
		cursor = db.rawQuery("select count(*) from " + VocabularyMeta.TABLE_NAME + " where " + VocabularyMeta.ANSWER_STATE + " = ?", new String[]{"2"});
		cursor.moveToFirst();
		wrongCounts = cursor.getInt(0);
		
		cursor.close();
		db.close();
		mOpenHelper.close();
		
		items[0] = "所有单词（共" + allCounts + "个）";
		items[1] = "未测试过的单词（共" + undoCounts + "个）";
		items[2] = "已测试过的单词（共" + doCounts + "个）";
		items[3] = "答对的单词（共" + correctCounts + "个）";
		items[4] = "答错的单词（" + wrongCounts + "个）";
		
		for(int i=0; i<5; i++){
			list.add(items[i]);
		}
		return list;
	}

}
